
@inject('storeService', 'App\App\Services\StorageService')

@php
    if(empty($activity->rule)){
        $basic="{}";
        $specs="[]";
        $specs_isopen = 0;
    }else{
        $rule = json_decode($activity->rule,true);
        if (empty($rule['basic'])){
             $basic="{}";
        }else{
            $basic = json_encode($rule['basic']);
        }
        if (empty($rule['spec'])){
             $specs="[]";
             $specs_isopen = 0;
        }else{
            $specs =$rule['spec']['isopen']==1? (isset($rule['spec']['list'])?$rule['spec']['list']:[]):[];
            $specs_isopen = $rule['spec']['isopen'];
            foreach ($specs as $key=> &$item){
                $item['id'] = $key;
            }
            unset($item);
            $specs = json_encode($specs);
        }

    }
    if (!empty($activity->shares)){
        $share = $activity->shares;
        $shareArray = json_decode($share,true);
        $shareArray['isopen'] = isset($shareArray['isopen'])?$shareArray['isopen']:0;
        $shareArray['icon'] = isset($shareArray['icon'])?$shareArray['icon']:'';
        $shareArray['qrcode'] = isset($shareArray['qrcode'])?$shareArray['qrcode']:'';
    }else{
        $shareArray = ['landindPage'=>0,'isopen'=>0,'icon'=>'','qrcode'=>''];
        $share = json_encode($shareArray);
    }
@endphp

<div class="text-left">
    <ul class="nav nav-icons" role="tablist">
        <li class="active">
            <a href="#activity_tab_0" role="tab" data-toggle="tab" aria-expanded="true">
                内容设置
            </a>
        </li>
        <li>
            <a href="#activity_tab_1" role="tab" data-toggle="tab" aria-expanded="true">
                奖品设置
            </a>
        </li>
        <li>
            <a href="#activity_tab_2" role="tab" data-toggle="tab" aria-expanded="true">
                自定义设置
            </a>
        </li>
    </ul>
</div>
<div class="tab-content">
    <div class="tab-pane active" id="activity_tab_0">
        <div class="card">
            <div class="content">
                <div class="form-group">
                    <label class="col-md-2 control-label">活动名称</label>
                    <input name="action" type="hidden" value="redpack_rain"/>
                    <div class="col-md-7">
                        <input class="form-control" type="text" ng-model="activity.name"
                               name="name" data-msg="请输入活动名称"
                        />
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-2 control-label">活动时间</label>
                    <div class="col-md-7">
                        <div class="row service-charges">

                            <div class="col-md-5 service-charges-name service-charges-name-0" style="padding-left: 15px;">
                                <input type="text" placeholder="开始时间"  name="startTime" data-msg="请输入开始时间" value="{{$activity->startTime}}" class="form-control datetimepicker">
                            </div>
                            <div class="col-md-5 service-charges-remark service-charges-remark-0">
                                <input type="text" placeholder="结束时间"   data-msg="请输入结束时间" name="endTime" value="{{$activity->endTime}}" class="form-control datetimepicker">
                            </div>

                        </div>
                    </div>
                </div>
                @php
                    if(!empty($activity->limit)){
                        $limit = json_decode($activity->limit,true);
                    }else{
                        $limit = [
                            'num'=>1,
                            'type'=>\App\Models\Activity\Activity::ACTIVITY_LIMIT_DAY_TYPE
                        ];
                    }
                @endphp
                <div class="form-group">
                    <label class="col-md-2 control-label">活动次数</label>
                    <div class="col-md-7">
                        <div class="row service-charges">
                            <label class="control-label pull-left" style="padding-left: 15px;">每人可抽奖</label>
                            <div class="col-md-9 input-group">
                                <input type="number" placeholder="参与次数"  value="{{$limit['num']}}"  name="limit[num]" min="1" data-msg="请输入参与次数" class="form-control">
                                <div class="input-group-addon">
                                    <select name="limit[type]" id="" class="">
                                        <option value="{{\App\Models\Activity\Activity::ACTIVITY_LIMIT_DAY_TYPE}}" @if($limit['type'] == \App\Models\Activity\Activity::ACTIVITY_LIMIT_DAY_TYPE) selected @endif >次/每日</option>
                                        <option value="{{\App\Models\Activity\Activity::ACTIVITY_LIMIT_ALL_TYPE}}" @if($limit['type'] == \App\Models\Activity\Activity::ACTIVITY_LIMIT_ALL_TYPE) selected @endif>次/活动全程</option>
                                    </select>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>

                <div class="form-group backgroundImg-container" style="display: none;">
                    <label class="col-md-2 control-label">更换背景</label>
                    <div class="col-md-7">
                        <input type="file" name="upfile" accept="image/gif,image/jpeg,image/png" data-target="uploadImageFile" data-for="backgroundImg" data-preview-file-type="text" class="form-control" value="" title="">
                        <input type="hidden" ng-model="activity.previewData.background" name="backgroundImg"  data-preview="{{$storeService->tomedia($activity->backgroundImg)}}" value="{{$activity->backgroundImg}}">
                        <span class="help-block">640*1200像素，支持PNG、JPG格式，小于100KB</span>
                    </div>
                </div>
                <div class="form-group backgroundColor-container" style="display: none;">
                    <label class="col-md-2 control-label">背景颜色</label>
                    <div class="col-md-7 input-group colorPicker colorpicker-component" data-format="alias">

                        <input type="text" value="{{$activity->backgroundColor}}" name="backgroundColor" class="form-control" />
                        <span class="input-group-addon"><i></i></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-2 control-label">活动介绍</label>
                    <div class="col-md-7">
                                                                            <textarea class="form-control tinymceEditor"
                                                                                      name="description"
                                                                            >{{$activity->description}}</textarea>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="tab-pane " id="activity_tab_1">

        <div class="card">
            <div class="content">
                <h5 class="">基础规则设定</h5>
                <p class="category">最低中奖条件，当抓取 <input type="number" min="1" ng-value="activity.basic.min_num" name="rule[basic][min_num]" style="width: 50px;">
                    个红包后才可按照奖品中奖概率中奖。</p>


                <p class="category">活动持续时间<input type="number" min="0" string-to-number="" ng-model="activity.previewData.time" ng-value="activity.basic.time" name="rule[basic][time]" style="width:50px;"> 秒</p>

            </div>
        </div>

        <div class="card">
            <div class="content table-responsive">
                <h5 class="">奖项设置</h5>
                <table class="table table-hover table-striped">
                    <thead>
                    <tr>
                        <th>图片</th>
                        <th>名称</th>
                        <th>中奖限制</th>
                        <th>库存限制</th>
                        <th>红包限额</th>
                        <th>中奖概率</th>
                        <th class="text-right">操作</th>
                    </tr>
                    </thead>
                    <tbody class="prizes-table">
                    <tr ng-repeat="pri in activity.prizes" data-index="@{{$index + 1}}">

                        <td class="td-image"><input type="hidden" name="prizes[@{{$index + 1}}][id]" value="@{{pri.id}}"><img
                                    ng-src="@{{pri.background_image}}" alt=""></td>
                        <td class="prize_name">@{{pri.name}}</td>
                        <td class="td-input"><input type="number" name="prizes[@{{$index + 1}}][winning_limit]"
                                                    value="@{{pri.winning_limit}}" min="0" tooltip data-title="限制每一个用户最多能抽中该奖品多少次，填0表示不限制"></td>
                        <td class="td-input"><input type="number" name="prizes[@{{$index + 1}}][stock_limit]" tooltip data-available_stock="@{{ pri.available_stock }}" data-title="最小可设置为0，最大不能超过@{{ pri.available_stock }}，如果为0，可能是因为其他活动使用该奖品，占用了库存（红包奖品为此次活动的总金额，微信红包每次只能发1-200元）"
                                                    value="@{{pri.stock_limit}}" min="0" ></td>
                        <td class="td-input"><input ng-if="pri.type == 'redpack'" type="number" name="prizes[@{{$index + 1}}][max_amount]" tooltip data-title="最小可设置为1，最大不能超过设置的库存限制"
                                                    value="@{{pri.max_amount}}"  data-max-msg="最大值不能超过200"></td>
                        <td class="td-input"><input type="number" name="prizes[@{{$index + 1}}][winning_probability]" tooltip data-title="中奖概率=奖品数/预估的参与人数*100%,最小可设置为0.最大可设置100% ,注:所有奖品概率总和不能大于100%"
                                                    value="@{{pri.winning_probability}}" min="0">%
                        </td>
                        <td class="td-actions text-right"><a class="btn btn-info btn-simple btn-xs"
                                                             ng-click="removeAddedPrices(pri)" href="javascript:;">删除</a></td>
                    </tr>


                    </tbody>
                </table>
            </div>
            <div class="footer">
                <a href="javascript:;" class="btn btn-fill btn-round btn-xs btn-warning" onclick="addPrizes()">添加奖品</a>
            </div>
        </div>

        {{--<div class="card">--}}
            {{--<div class="content specContent">--}}
                {{--<div>--}}
                    {{--<h5 class="" style="float: left;margin-right: 10px;">--}}
                        {{--特殊规则设置--}}
                    {{--</h5>--}}
                    {{--<div class="" bootstrap-switch data-ischecked="@{{activity.specs_isopen}}" style="margin-top: 5px;" data-on-label="<i class='fa fa-check'></i>"--}}
                         {{--data-off-label="<i class='fa fa-times'></i>" data-on-color="success">--}}
                        {{--<input type="checkbox" name="rule[spec][isopen]"  value="1" >--}}
                    {{--</div>--}}
                    {{--<a href="javascript:;" style="margin-top: 10px;" ng-if="activity.specs_isopen == 1" id="addSpec" ng-click="addSpec()"--}}
                       {{--class="pull-right text-danger specIsShow">+新增</a>--}}
                {{--</div>--}}
                {{--<div class="clearfix"></div>--}}
                {{--<div class="table-responsive specIsShow" id="specContentTable" ng-if="activity.specs_isopen == 1">--}}
                    {{--<table class="table spec-table">--}}
                        {{--<tbody>--}}
                        {{--<tr class="spec-list" ng-repeat="spec in activity.specs" data-id="@{{spec.id}}">--}}
                            {{--<td >--}}
                                {{--<div class="form-group"><label class="control-label pull-left" for="">每个用户在</label>--}}
                                    {{--<div class="pull-left" style="position: relative;"><input type="text" placeholder="开始时间" ng-value="spec.start"--}}
                                                                                              {{--required=""--}}
                                                                                              {{--name="rule[spec][list][@{{spec.id}}][start]"--}}
                                                                                              {{--data-msg="请输入开始时间"--}}
                                                                                              {{--class="form-control " date-time-picker>--}}
                                    {{--</div>--}}
                                    {{--<label class="control-label pull-left" for="">-</label>--}}
                                    {{--<div class="pull-left" style="position: relative;"><input type="text" placeholder="结束时间" ng-value="spec.end"--}}
                                                                                              {{--required="" data-msg="请输入结束时间"--}}
                                                                                              {{--name="rule[spec][list][@{{spec.id}}][end]"--}}
                                                                                              {{--class="form-control " date-time-picker>--}}
                                    {{--</div>--}}
                                    {{--<label class="control-label pull-left" for="">100%抽中</label>--}}
                                    {{--<div class="pull-left"><select name="rule[spec][list][@{{spec.id}}][prize]" string-to-number="" ng-model="spec.prize" class="form-control"--}}
                                                                   {{--data-style="btn-default btn-block"--}}
                                                                   {{--data-menu-style="dropdown-blue">--}}
                                            {{--<option ng-repeat="przi in $parent.activity.prizes" ng-selected="$parent.spec.prize ==przi.id" value="@{{przi.id}}">@{{przi.name}}</option>--}}
                                        {{--</select></div>--}}
                                    {{--<div class="pull-left spec-number-input"><input type="number" ng-value="spec.times"--}}
                                                                                    {{--name="rule[spec][list][@{{spec.id}}][times]" rel="tooltip"--}}
                                                                                    {{--title="" class="form-control"--}}
                                                                                    {{--data-original-title="不能超过中奖限制"></div>--}}
                                    {{--<label class="control-label pull-left" for="">次</label></div>--}}
                            {{--</td>--}}
                            {{--<td class="text-right">--}}
                                {{--<div class="form-group"><a class="control-label text-danger btn btn-simple" href="javascript:;"--}}
                                                           {{--ng-click="removeSpec(spec)">删除</a></div>--}}
                            {{--</td>--}}
                        {{--</tr>--}}
                        {{--</tbody>--}}
                    {{--</table>--}}
                {{--</div>--}}

            {{--</div>--}}
        {{--</div>--}}
    </div>
    <div class="tab-pane " id="activity_tab_2">
        <div class="card">
            <div class="content">
                <div class="form-group" ng-show="activity.category == 1">
                    <label class="col-md-2 control-label">开启分享</label>
                    <div class="col-md-7" >
                        <div class="switch" data-on-label="是" data-off-label="否" data-on-color="success">
                            <input type="checkbox" name="share[isopen]" value="1" @if($shareArray['isopen'] == 1) checked @endif>
                        </div>

                    </div>
                </div>
                <!--
                <div class="form-group" ng-if="activity.category == 2">
                    <div class="col-md-7 col-md-offset-2" >
                        <label class="checkbox-inline">
                            <input type="checkbox" ng-checked="activity.share.landindPage == 1" ng-click="selectLandindPage(1)" name="share[landindPage]" value="1"> 活动落地页
                        </label>
                        <label class="checkbox-inline">
                            <input type="checkbox" ng-checked="activity.share.landindPage == 2" ng-click="selectLandindPage(2)" name="share[landindPage]" value="2"> 自定义落地页
                        </label>
                    </div>
                </div>
                -->
                <div class="form-group" ng-if="activity.category == 2" ng-show="activity.share.landindPage == 2">
                    <label class="col-md-2 control-label">落地页面</label>
                    <div class="col-md-7">
                        <input class="form-control" type="text" ng-value="activity.share.share_url"
                               name="share[share_url]" placeholder="示例：http://www.baidu.com"
                        />
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-2 control-label">分享图标</label>
                    <div class="col-md-7">
                        <input type="file" name="upfile" accept="image/gif,image/jpeg,image/png" data-for="share[icon]" file-upload data-preview-file-type="text" class="form-control" value="" title="">
                        <input type="hidden" name="share[icon]" data-preview="{{$storeService->tomedia($shareArray['icon'])}}" value="{{$shareArray['icon']}}">
                        <span class="help-block">200 * 200像素，支持PNG、JPG格式，小于20KB</span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-2 control-label">分享标题</label>
                    <div class="col-md-7">
                        <input class="form-control" type="text" ng-value="activity.share.title"
                               name="share[title]"
                        />
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-2 control-label">分享文案</label>
                    <div class="col-md-7">
                                                                            <textarea class="form-control" rows="3"
                                                                                      name="share[description]"
                                                                            >@{{activity.share.description}}</textarea>
                    </div>
                </div>
                <div class="form-group" ng-if="activity.category == 1">
                    <label class="col-md-2 control-label">上传二维码</label>
                    <div class="col-md-7">
                        <input type="file" name="upfile" accept="image/gif,image/jpeg,image/png" data-for="share[qrcode]" file-upload data-preview-file-type="text" class="form-control" value="" title="">
                        <input type="hidden" name="share[qrcode]" data-preview="{{$storeService->tomedia($shareArray['qrcode'])}}" value="{{$shareArray['qrcode']}}">
                        <span class="help-block">200 * 200像素，支持PNG、JPG格式，小于20KB</span>
                    </div>
                </div>
                <div class="form-group" ng-if="activity.category == 2" ng-show="activity.share.landindPage == 1">
                    <label class="col-md-2 control-label">底部图片</label>
                    <div class="col-md-7">
                        <input type="file" name="upfile" accept="image/gif,image/jpeg,image/png" data-for="share[qrcode]" file-upload data-preview-file-type="text" class="form-control" value="" title="">
                        <input type="hidden" name="share[qrcode]" data-preview="{{$storeService->tomedia($shareArray['qrcode'])}}" value="{{$shareArray['qrcode']}}">
                        <span class="help-block">640 * 98像素，支持PNG、JPG格式，小于50KB</span>
                    </div>
                </div>
                <div class="form-group" ng-if="activity.category == 2" ng-show="activity.share.landindPage == 1">
                    <label class="col-md-2 control-label">iOS下载地址</label>
                    <div class="col-md-7">
                        <input class="form-control" type="text" ng-value="activity.share.download.ios"
                               name="share[download][ios]"
                        />
                    </div>
                </div>
                <div class="form-group" ng-if="activity.category == 2" ng-show="activity.share.landindPage == 1">
                    <label class="col-md-2 control-label">安卓下载地址</label>
                    <div class="col-md-7">
                        <input class="form-control" type="text" ng-value="activity.share.download.android"
                               name="share[download][android]"
                        />
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>


<script type="text/javascript">

    initUploadImageFile();
    initUploadMulImageFile();
    initTinymce();
    initDatetimepicker();
    initTimepicker();
    initColorPickerAndSwitch();


    require(['angular','directives'],function (angular) {
        var app = angular.module('app', ['directives']);
        app.controller('ActivityController',['$scope','$compile','$timeout',function ($scope,$compile,$timeout) {

            @if(!empty($activity->id))
                $scope.activity = {
                name:'{{$activity->name}}',
                template:'',
                category:'{{$activity->category}}',
                basic:{!!$basic!!},
                specs:{!! $specs !!},
                prizes:{!! json_encode($activity_pris) !!},
                preview_src:'',
                specs_isopen:{{$specs_isopen}},
                previewData:{},
                share:{!! $share !!}
            };
            var tpl = $('a[data-template="{{$activity->template_id}}"]').data('detail');
            if (tpl.isBackgroundImage == 1){
                $('.backgroundImg-container').show();
            }else {
                $('.backgroundImg-container').hide();
            }
            if (tpl.isBackgroundColor == 1){
                $('.backgroundColor-container').show();
            }else {
                $('.backgroundColor-container').hide();
            }

                    @else
            var isBackgroundImage = {{$ativity_template->isBackgroundImage}};
            var isBackgroundColor = {{$ativity_template->isBackgroundColor}};
            var category = $('input[name="category"]').val();

            $scope.activity = {
                name:'',
                template:'',
                category:category,
                basic:{!!$basic!!},
                specs:[],
                prizes:[],
                preview_src:'',
                specs_isopen:0,
                previewData:{},
                share:{
                    landindPage:0
                }
            };

            if (isBackgroundImage == 1){
                $('.backgroundImg-container').show();
            }else {
                $('.backgroundImg-container').hide();
            }
            if (isBackgroundColor == 1){
                $('.backgroundColor-container').show();
            }else {
                $('.backgroundColor-container').hide();
            }
            $('#wizardCard').bootstrapWizard('next');
            @endif



                    @if(!empty($activity->model_id))
                $scope.activity.previewData = {
                'time':$scope.activity.basic.time,
                'background':'{{$activity->backgroundImg}}'
            }
            $scope.activity.preview_src="/{{$activity->model->rule}}/activity/preview/{{$activity->model->rule}}/{{$activity->template->template}}"
            @else
                $scope.activity.preview_src="/{{$ativity_model->rule}}/activity/preview/{{$ativity_model->rule}}/{{$ativity_template->template}}"
            @endif

            /**
             * 选择 活动落地页 或则 自定义落地页
             */
            $scope.selectLandindPage =function (landindPage) {
                if ($scope.activity.share.landindPage == landindPage){
                    $scope.activity.share.landindPage = 0;
                }else {
                    $scope.activity.share.landindPage = landindPage;
                }
            };
            $scope.previewDataFunc = function () {
                return JSON.stringify($scope.activity.previewData);
            };

            /**
             * @desc 上传活动背景图，试图浏览
             * @param result
             * @param input_name
             */
            window.uploadFilesSuccess = function (result,input_name) {
                if (input_name == 'backgroundImg'){
                    $timeout(function () {
                        console.log($scope.activity);
                        $scope.activity.previewData['background'] = result.url;
                    })
                }
            }

            $scope.$watch('previewDataFunc()',function (newData) {
                if (newData){
                    newData = JSON.parse(newData);
                    $urlPath = parseURL($scope.activity.preview_src);
                    $scope.activity.preview_src =$urlPath['path']+'?'+$.param(newData);
                }
            });

            $scope.removeAddedPrices =function (obj) {
                _.remove($scope.activity.prizes,function (n) {
                    return n.id ==obj.id;
                });
                _.remove($scope.activity.specs,function (n) {
                    return n.prize ==obj.id;
                });
                var exclude = _.map($scope.activity.prizes, 'id');
                $('.prizes-table').attr('data-exclude',exclude.join(','));
            }

            /**
             * @desc 奖品设置，添加奖项设置后，需要特殊规则设置
             * @returns {boolean}
             */
            $scope.addSpec = function () {
                if ($scope.activity.prizes.length == 0) {
                    utils.showNotification('请先添加奖品,然后再设置特殊规则', 3);
                    return false;
                }
                var spec = {
                    start:'',
                    end:'',
                    prize:$scope.activity.prizes[0].id,
                    times:0
                };
                if ($scope.activity.specs.length >0){
                    spec['id'] = _.last($scope.activity.specs)['id']+1;
                }else {
                    spec['id'] = 0;
                }
                $scope.activity.specs.push(spec);
            }

            /**
             * @desc 奖品设置，需要删除特殊规则设置
             * @param spec
             */
            $scope.removeSpec = function (spec) {
                _.remove($scope.activity.specs,function (n) {
                    return n.id == spec.id;
                });

            }


            /**
             * @desc 验证数据，并提交
             */
            $scope.onFinishWizard =function() {
                //here you can do something, sent the form to server via ajax and show a success message with swal
                tinyMCE.triggerSave();
                if (valideActivityForm()){
                    var obj = $('#activityForm').serialize();
                    $.isLoading({text:'数据提交中，请稍后。。。'});
                    $.post(location.href,obj,function (res) {
                        $.isLoading('hide');
                        if(res.code == 0){
                            var notify = utils.showNotification('保存成功', 2);
                            setTimeout(function () {
                                notify.close();
                                window.location.href="/web/activity/index";
                            },2000);
                        }else {
                            utils.showNotification(res.message,3);
                        }
                    });

                }

            }

            /**
             * @desc 是否开启特殊设置
             */
            $scope.openSpec=function() {
                $scope.activity.specs_isopen = $scope.activity.specs_isopen == 1?0:1;
            };

            $scope.$on('bootstrap-switch-change',function (event,data) {
                $scope.$apply(function () {
                    if (data.value){
                        $scope.activity.specs_isopen = 1;
                    }else {
                        $scope.activity.specs_isopen = 0;
                    }
                });

            })

            /**
             * @desc  微信支付，支付宝支付
             */
            window.operateEvents = {
                'click .selectPrize':function (e,value,row) {

                    $scope.$apply(function () {
                        row.winning_limit = 0;
                        row.stock_limit = 0;
                        row.winning_probability = 0;
                        row.available_stock =row.available_stock || 0;
                        row.max_amount = 0;
                        if (row.type_code == 'wechat' || row.type_code == 'alipay'){
                            row.type ="redpack";
                        }else {
                            row.type ="other";
                        }
                        $scope.activity.prizes.push(row);
                        var exclude = _.map($scope.activity.prizes, 'id');
                        $('.prizes-table').attr('data-exclude',exclude.join(','));
                    });
                }
            };



            /**
             * @desc 验证
             * @returns {boolean}
             */
            function valideActivityForm() {
                var form = $('#activityForm');
                var category =$('input[name="category"]').val();
                if (!form.find('input[name=name]').val()){
                    utils.showNotification('请输入活动名称',3);
                    return false;
                }
                if (!form.find('input[name=startTime]').val()){
                    utils.showNotification('请输入活动开始时间',3);
                    return false;
                }
                if (!form.find('input[name=endTime]').val()){
                    utils.showNotification('请输入活动结束时间',3);
                    return false;
                }
                if (moment(form.find('input[name=endTime]').val()).unix()< moment(form.find('input[name=startTime]').val()).unix()){
                    utils.showNotification('活动结束时间不能小于开始时间',3);
                    return false;
                }
                if(form.find('input[name="limit[num]"]').val() ==""){
                    utils.showNotification('请输入参与活动次数',3);
                    return false;
                }

                if (typeof valideRuleForm !== 'undefined' && $.isFunction(valideRuleForm)){
                    var res = valideRuleForm();
                    if (!res){
                        return false;
                    }
                }
                if ($scope.activity.prizes.length > 0 && $scope.activity.specs_isopen == 1){
                    var isSuccess = true,errmsg="";

                    _.each($scope.activity.specs,function (v) {
                        var start = $('input[name="rule[spec][list]['+v.id+'][start]"]').val();
                        var end = $('input[name="rule[spec][list]['+v.id+'][end]"]').val();
                        if (!start){
                            isSuccess = false;
                            errmsg = "请设置特殊规则的开始时间";
                            return false;
                        }
                        if (!end){
                            isSuccess = false;
                            errmsg = "请设置特殊规则的结束时间";
                            return false;
                        }
                        if (moment(start).unix() >= moment(end).unix()){
                            isSuccess = false;
                            errmsg = "特殊规则的开始时间不能大于或等于结束时间";
                            return false;
                        }
                    })
                    if (!isSuccess){
                        utils.showNotification(errmsg,3);
                        return false;
                    }
                }


                if (category == 1){
                    if (form.find('input[name="share[isopen]"]').is(':checked')){
                        if (!form.find('input[name="share[icon]"]').val()){
                            utils.showNotification('请上传分享图标',3);
                            return false;
                        }
                        if (!form.find('input[name="share[title]"]').val()){
                            utils.showNotification('请输入分享标题',3);
                            return false;
                        }
                        if (!form.find('textarea[name="share[description]"]').val()){
                            utils.showNotification('请输入分享文案',3);
                            return false;
                        }
                        if (!form.find('input[name="share[qrcode]"]').val()){
                            utils.showNotification('请上传二维码',3);
                            return false;
                        }
                    }
                }else {
                    if (!form.find('input[name="share[icon]"]').val()){
                        utils.showNotification('请上传分享图标',3);
                        return false;
                    }
                    if (!form.find('input[name="share[title]"]').val()){
                        utils.showNotification('请输入分享标题',3);
                        return false;
                    }
                    if (!form.find('textarea[name="share[description]"]').val()){
                        utils.showNotification('请输入分享文案',3);
                        return false;
                    }

                    if (form.find('input[name="share[landindPage]"]:checked').val() == 1){
                        if (!form.find('input[name="share[qrcode]"]').val()){
                            utils.showNotification('请上传底部图片',3);
                            return false;
                        }
                        if (!form.find('input[name="share[download][ios]"]').val()){
                            utils.showNotification('请输入IOS下载地址',3);
                            return false;
                        }
                        if (!form.find('input[name="share[download][android]"]').val()){
                            utils.showNotification('请输入安卓下载地址',3);
                            return false;
                        }
                    }
                    if (form.find('input[name="share[landindPage]"]:checked').val() == 2){
                        if (!form.find('input[name="share[share_url]"]').val()){
                            utils.showNotification('请自定义落地页面地址',3);
                            return false;
                        }
                    }
                }

                return true;
            }



        }]);
        angular.bootstrap(document, ['app']);
    });


    /**
     * 验证各个活动奖品设置中输入的表单数据
     */
    function valideRuleForm() {
        var form = $('#activityForm');
        if (form.find('input[name="rule[basic][min_num]"]').val() == '') {
            utils.showNotification('请输入最低抓取红包数才能触发中奖', 3);
            return false;
        }
        if (form.find('input[name="rule[basic][time]"]').val() == '') {
            utils.showNotification('请输入单场活动持续时间', 3);
            return false;
        }
        if (form.find('.prizes-table tr').length == 0) {
            utils.showNotification('请添加活动奖品', 3);
            return false;
        }
        var probability = 0,hasError = false;
        $('.prizes-table tr').each(function (i,v) {
            var index = $(v).data('index');
            var stock_limit = $('input[name="prizes['+index+'][stock_limit]"]').val();
            var prizename = $(v).find('.prize_name').text();
            var available_stock = $('input[name="prizes['+index+'][stock_limit]"]').attr('data-available_stock');
            if ($('input[name="prizes['+index+'][max_amount]"]').length >0){
                var max_amount = parseFloat($('input[name="prizes['+index+'][max_amount]"]').val());
                if (max_amount<1 ||max_amount>200 || max_amount>stock_limit){
                    utils.showNotification(prizename+'红包限额不能超过库存限制，并且只能设置在1-200范围', 3);
                    hasError = true;
                    return false;
                }
            }
            if (parseInt(stock_limit)>parseInt(available_stock)){
                utils.showNotification(prizename+'奖品的库存限制不能大于可用库存', 3);
                hasError = true;
                return false;
            }
            probability += parseFloat($('input[name="prizes['+index+'][winning_probability]"]').val());
        });
        if (hasError){
            return false;
        }
        if (probability >100){
            utils.showNotification('中奖概率不能大于100', 3);
            return false;
        }
        return true;
    }



    function addPrizes() {
        var addprize = utils.modal('添加奖品', function (ele) {
            var category = $('input[name="category"]').val();
            var html = '<table class="table" id="prizesTable"><thead><tr><th data-field="name">奖品名称</th><th data-field="prize_type.name" data-formatter="typeFormatter">类型</th><th data-formatter="expiredFormatter">有效期</th><th class="text-center" data-formatter="stockFormatter">可用/库存</th><th data-field="actions" class="td-actions text-center" data-events="operateEvents" data-formatter="operateFormatter">操作</th></tr></thead></table>';
            ele.find('.modal-body').html(html);
            var exclude = $('.prizes-table').attr('data-exclude') || '';
            var table_option = {
                searchAlign: 'left',
                queryParams: function (query) {
                    query['category'] = category;
                    query['exclude'] = exclude;
                    return query;
                },
                url: '/web/prize/queryPrizes'
            }
            default_table_option = $.extend(default_table_option, table_option);
            $('#prizesTable').bootstrapTable(default_table_option);
            $('#prizesTable').on('click', '.selectPrize', function () {
                addprize.modal('hide');
            })
        }, false, function (res) {
            if (res == 1) {
                addprize.modal('hide');
            }
        })

    }


    function typeFormatter(value, row) {
        return row.prize_type.name;
    }
    function expiredFormatter(value, row) {

        return (row.expired_start||'-') + '<br/>' + (row.expired_end||'-');
    }
    function stockFormatter(value, row) {
        var available_stock = row.available_stock ? row.available_stock : 0;
        var stock_number = row.stock_number ? row.stock_number : 0;
        return available_stock + '/' + stock_number;
    }
    function operateFormatter(value, row) {
        return '<a class="btn btn-warning btn-fill selectPrize">选取</a>';
    }

</script>